package br.unesp.rc.lista01.ex_03.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import br.unesp.rc.lista01.ex_03.beans.Cliente;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.ext.Db4oException;

public class ClienteDAOImp implements ClienteDAO {

    public ClienteDAOImp(){}

    public boolean addCliente(Cliente cliente) {
    	ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "database.db4o");
		try {
			db.store(cliente);
		} catch (Db4oException e) {
			throw new RuntimeException(e);
		} finally {
			db.close();
		}
        System.out.println(cliente.getNome() + " foi adicionado!!");
        return true;
    }

    public boolean removeCliente(String cpf) {
    	ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "database.db4o");
		try {
			Cliente clienteToDelete = new Cliente();
			clienteToDelete.setCpf(cpf);
			ObjectSet<Cliente> objects = db.queryByExample(clienteToDelete);
			for (Cliente cliente: objects) {
				db.delete(cliente);
			}
		} catch (Db4oException e) {
			throw new RuntimeException(e);
		} finally {
			db.close();
		}
		return true;
    }
    
    private Cliente getCliente(String cpf) {
    	Cliente cliente;
    	ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "database.db4o");
		try {
			Cliente clienteToFind = new Cliente();
			clienteToFind.setCpf(cpf);
			ObjectSet<Cliente> objects = db.queryByExample(clienteToFind);
			cliente = objects.next();
		} catch (Db4oException e) {
			throw new RuntimeException(e);
		} finally {
			db.close();
		}
		return cliente;
    }
    
    public Cliente escolherCliente() {
		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "database.db4o");
		Scanner scanner = new Scanner(System.in);
		Cliente retorno;
        try {
        	ObjectSet<Cliente> objects = db.query(Cliente.class);
        	System.out.println("Nome\tCPF");
        	for (Cliente cliente: objects) {
        		System.out.println(cliente.getNome() + "\t" + cliente.getCpf());
        	}
        } catch (Db4oException e) {
			throw new RuntimeException(e);
		} finally {
			db.close();
		}
        System.out.print("CPF do cliente: ");
        retorno = getCliente(scanner.nextLine());
        return retorno;
	}
    
    public List<Cliente> listCliente() {
		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "database.db4o");
		List<Cliente> clientes = new ArrayList<Cliente>();
        try {
        	ObjectSet<Cliente> objects = db.query(Cliente.class);
        	for (Cliente cliente: objects) {
        		clientes.add(cliente);
        	}
        } catch (Db4oException e) {
			throw new RuntimeException(e);
		} finally {
			db.close();
		}
        return clientes;
	}

}
